package cn.owng.cli.db;

import cn.owng.cli.Env;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import picocli.CommandLine;

import java.sql.Connection;
import java.util.concurrent.Callable;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Slf4j
@CommandLine.Command(name = "drop", description = "删除数据库")
public class Drop implements Callable<Integer> {

    @CommandLine.Option(names = {"-c", "--confirm"}, description = "确认删除数据库？确认删除请输入Y，否则请输入其他。", interactive = true, echo = true, required = true)
    private String confirm;

    @Override
    public Integer call() throws Exception {
        if ("Y".equalsIgnoreCase(confirm)) {
            Env.Db db = Env.db();
            try (HikariDataSource ds = new HikariDataSource()) {
                ds.setJdbcUrl(db.getUrl());
                ds.setUsername(db.getUsername());
                ds.setPassword(db.getPassword());
                Connection con = ds.getConnection();
                String sql = "drop database " + db.getDatabase();
                log.info("执行 SQL: {}", sql);
                con.prepareStatement(sql).execute();
            }
        } else {
            log.info("取消删除数据库");
        }
        return 0;
    }
}
